package com.stedu.controller;
//备份


import com.stedu.bean.ChuKu;
import com.stedu.bean.PeiJian;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.mapper.ChuKuMapper;
import com.stedu.mapper.PeiJianMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin/chuku")
public class ChuKuController {

    @Autowired
    private ChuKuMapper chuKuMapper;
    @Autowired
    private PeiJianMapper peiJianMapper;

    @PostMapping
    @Transactional
    public RespBean insert(@Validated @RequestBody ChuKu chuKu) throws SteduException {
        try {
            // 1. 插入出库记录
            boolean insertSuccess = chuKuMapper.insert(chuKu);
            if (!insertSuccess) {
                return RespBean.error("添加失败，插入出库记录异常");
            }

            // 2. 获取配件信息
            PeiJian part = peiJianMapper.selectByPid(chuKu.getPartId());
            if (part == null) {
                return RespBean.error("添加失败，配件不存在");
            }

            // 3. 检查库存是否足够
            if (part.getStock() < chuKu.getOutQty()) {
                return RespBean.error("添加失败，库存不足");
            }

            // 4. 计算新库存并更新
            part.setStock(part.getStock() - chuKu.getOutQty());
            boolean updateSuccess = peiJianMapper.update(part);
            if (!updateSuccess) {
                return RespBean.error("添加失败，更新库存异常");
            }

            // 添加这行：当所有操作成功时返回成功响应
            return RespBean.ok("添加成功，库存已更新");

        } catch (Exception e) {
            // 发生异常时回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RespBean.error("添加失败：" + e.getMessage());
        }
    }
    @GetMapping
    @CrossOrigin(origins = "http://localhost:5173") // 允许来自http://localhost:5173的请求
    public List<PeiJian> getAllParts() {
        return peiJianMapper.selectAllParts();
    }
}
